var modifyOrAddFlag;
var analysisReason = new Array();
analysisReason[0] = 'ESB到原服务间网络中断';
analysisReason[1] = '原服务所在服务器宕机';
analysisReason[2] = '原程序系统异常';
analysisReason[3] = '原程序数据库异常';
analysisReason[4] = 'ESB本身故障';

var rowData;
$(document)
		.ready(
				function() {
					urlParamObj = getParamobjFromUrl();				
					// 由主界面转来的 start==========================
					if(urlParamObj.fieldSystemId){
						$('#chkToday').attr("checked", false);
						$('#chkIoslation').attr("checked", true);
					}
					// 由主界面转来的 end=============================

					$('#winExceptionIfAnalysis').window('close');
					$('#winWorkOrder').window('close');
					// 请求结果下拉框
					$('#comboxAlarmType').combobox(
							{
								url : BASE_URL_DATA_DICTIONARY_VALUE_SEARCH
										+ '/findByTypeCode?typeCode='
										+ DDTC_ALARM_TYPE + '&v='
										+ Math.random(),
								valueField : 'valueCode',
								textField : 'valueName',
								editable : false,
								method : 'get',
								loadFilter : function(data) {
									var allCheck = {
										'valueCode' : '',
										'valueName' : '全部'
									};
									data.unshift(allCheck);
									return data;
								}
							});
					// 请求结果下拉框
					$('#comboxField')
							.combobox(
									{
										url : BASE_URL_FIELD_SEARCH
												+ '/findAllOfCurrentUserCanManage'
												+ '?v=' + Math.random(),
										valueField : 'id',
										textField : 'name',
										editable : false,
										method : 'get',
										loadFilter : function(data) {
											var allCheck = {
												'id' : '',
												'name' : '请选择'
											};
											if (data.content) {
												data.content.unshift(allCheck);
											} else {
												return data;
											}
											return data.content;
										},
										onSelect : function(record) {
											comboxSystem
													.combobox(
															{
																disabled : false,
																method : 'get',
																queryParams : {
																	fieldId : record.id
																},
																url : BASE_URL_FIELD_SYSTEM_SEARCH
																		+ '/findByFieldOfCurrentUserCanManage'
																		+ '?v='
																		+ Math
																				.random(),
																valueField : 'id',
																textField : 'name',
																data : '',
																loadFilter : function(
																		data) {

																	var allCheck = {
																		'id' : '',
																		'name' : '请选择'
																	};
																	data.content
																			.unshift(allCheck);
																	return data.content;
																},
																onSelect : function(
																		record) {
																	$('#comboxInterface')
																			.combobox({
																				disabled : false,
																				method : 'get',
																				queryParams : {
																					fieldSystemId : record.id
																				},
																				url : BASE_URL_SYSTEM_INTERFACE_SEARCH
																						+ '/findByOwnerFieldSystem_Id'
																						+ '?v='
																						+ Math
																								.random(),
																				valueField : 'id',
																				textField : 'jobName',
																				data : '',
																				loadFilter : function(
																						data) {
																					if (data[0].id == "") {
																						return data;
																					}
																					var allCheck = {
																						'id' : '',
																						'jobName' : '请选择'
																					};
																					data
																							.unshift(allCheck);
																					return data;

																				},
																				onLoadSuccess : function() {
																					$(
																							'#comboxInterface')
																							.combobox(
																									'setValue',
																									'');
																				}
																			});
																},
																onLoadSuccess : function() {
																	$(
																			'#comboxInterface')
																			.combobox(
																					'setValue',
																					'');
																	if(urlParamObj.fieldSystemId)
																	{
																		comboxSystem.combobox('setValue',urlParamObj.fieldSystemName? decodeURI(urlParamObj.fieldSystemName):"");
																		comboxSystem.combobox("select",urlParamObj.fieldSystemId);
																		urlParamObj.fieldSystemId = '';
																	}

																},
															// onChange :
															// function(
															// newValue,
															// oldValue) {
															// $(
															// '#datagrid4if')
															// .datagrid(
															// 'reload');
															// }
															}).load();
											$('#comboxInterface').combobox({
												disabled : true,
												valueField : 'id',
												textField : 'jobName',
												editable : false,
												url : '',
												data : [],
												loadFilter : function(data) {
													var allCheck = {
														id : '',
														jobName : '请选择',
														'selected' : 'true'
													};
													data.unshift(allCheck);
													return data;
												}
											});
										},
										onLoadSuccess:function(){
											if(urlParamObj.fieldName){
												var datas = $('#comboxField').combobox('getData');
												for(var i=0;i< datas.length;i++){
													if(datas[i].name == decodeURI(urlParamObj.fieldName)){
														$('#comboxField').combobox('select',datas[i].id);
													}
												}
											}
									    }
									});

					var comboxSystem = $('#comboxSystem').combobox({
						disabled : true,
						valueField : 'id',
						textField : 'name',
						editable : false,
						url : '',
						data : [],
						loadFilter : function(data) {
							var allCheck = {
								id : '',
								name : '请选择',
								'selected' : 'true'
							};
							data.unshift(allCheck);
							return data;
						}

					});

					$("#datagrid")
							.datagrid(
									{
										url : BASE_URL_API
												+ '/serviceAlarmManagement/findServiceAlarmManagementInfo?v='
												+ Math.random(),
										method : 'get',
										autoRowHeight : true,
										singleSelect : true,
										striped : true,
										nowrap : false,
										pageSize : 20,
										pageList : [ 10, 20, 50, 100 ],
										columns : [ [

												{
													field : 'fieldName',
													title : '所属领域',
													width : 20,
													align : 'center'
												},
												{
													field : 'systemName',
													title : '所属系统',
													width : 20,
													align : 'center'
												},
												{
													field : 'ifName',
													title : '接口名称',
													width : 50,
													align : 'center'
												},
												{
													field : 'alarmLevel',
													title : '告警等级',
													width : 12,
													align : 'center',
													formatter : function(value,
															rowData, rowIndex) {
														return value == '1' ? '<img src="../../../../images/icons/general.png"  height="24" width="24">'
																: value == '2' ? '<img src="../../../../images/icons/importance.png"  height="24" width="24">'
																		: '<img src="../../../../images/icons/urgent.png"  height="24" width="24">';
													}
												},
												{
													field : 'alarmType',
													title : '告警类型',
													width : 15,
													align : 'center',
													formatter : function(value,
															rowData, rowIndex) {
														return value == '1' ? '请求超时'
																: (value == '2' ? '请求超限'
																		: 'Http400错误');
													}
												},
												{
													field : 'errorDateStr',
													title : '发生时间',
													width : 30,
													align : 'center'
												},
												{
													field : 'analyze',
													title : '异常分析',
													width : 15,
													align : 'center',
													formatter : function(value,
															rowData, rowIndex) {
														return '<a href="javascript:void(0)" class="default_btn" onclick="analyze('
																+ rowIndex
																+ ')">分析</a>';
													}
												},
												{
													field : 'malfunction',
													title : '处理故障',
													width : 15,
													align : 'center',
													formatter : function(value,
															rowData, rowIndex) {
														return '<a href="javascript:void(0)" class="default_btn" onclick="showWorkOrder('
																+ rowIndex
																+ ')">处理</a>';
													}
												},
												{
													field : 'isIsolation',
													title : '是否隔离',
													width : 15,
													align : 'center',
													formatter : function(value,
															rowData, rowIndex) {
														if (value == '0') {
															return '<a href="javascript:void(0)" class="default_btn" onclick="isolation('
																	+ rowIndex
																	+ ')">隔离</a>';
														}else if(value == '1'){
															return '<a href="#" class="default_btn fl" onclick="cancelIsolation('
															+ rowIndex
															+ ')">取消隔离</a>';
														}
														return "";
													}
												} ] ],
										pagination : true,
										onSelect : function(rowIndex, rowData) {
										},
										onUnselect : function() {
										},
										loadFilter : function(data) {
											// alert("inData:"
											// + JSON.stringify(data));
											return {
												total : data.totalElements,
												rows : data.content
											};
										},
										onBeforeLoad : function(param) {
											param.page -= 1;
											param.size = param.rows;
											delete param.rows;

											param.sort = 'CREATED_DATE desc';

											var systemId = $('#comboxSystem')
													.combobox('getValue');
											if (systemId != "") {
												param.systemId = systemId;
											}
											var fieldId = $('#comboxField')
													.combobox('getValue');
											if (fieldId != "") {
												param.fieldId = fieldId;
											}
											var alarmType = $(
													'#comboxAlarmType')
													.combobox('getValue');
											if (alarmType != "") {
												param.alarmType = alarmType;
											}
											var startDateTime = $(
													"#txtStartDateTime")
													.datebox('getValue');
											if (startDateTime != "") {
												param.startDateTime = startDateTime;
											}
											var endDateTime = $(
													"#txtEndDateTime").datebox(
													'getValue');
											if (endDateTime != "") {
												param.endDateTime = endDateTime;
											}
											var today = false;
											var sevenBeforeDate = false;
											var isolation = '';
											$(
													"input:checkbox[name='chboxPeriod']:checked")
													.each(
															function(i) {
																if ($(this)
																		.val() == '0') {
																	today = true;
																} else if ($(
																		this)
																		.val() == '1') {
																	sevenBeforeDate = true;
																}
															});
											$(
													"input:checkbox[name='chboxStatus']:checked")
													.each(
															function(i) {
																if (isolation != '') {
																	isolation = '';
																} else {
																	isolation = $(
																			this)
																			.val();
																}
															});
											param.today = today;
											param.sevenBeforeDate = sevenBeforeDate;
											param.isolation = isolation;
										},
										onLoadError : function(e) {
											// alert(JSON.stringify(e));
											$.messager.alert('错误', '<p>服务异常，'
													+ e.responseJSON.message
													+ '，请稍后重试或联系管理员!</p>',
													'error');
										}
									});

					$("#datagrid").datagrid('getPager').pagination({
						displayMsg : '当前显示从 [{from}] 到 [{to}] 共[{total}]条记录'
					});
					$(".panel-tool-close, #instance_cancel").click(function(e) {
						$("body").css("overflow-x", "inherit")
					});
					// 定时刷新
					loopRefresh();
				});


// 提交工单
function commitWorkOrder() {
	var errorAnalysis = "";
	$("input:checkbox[name='chboxErrorAnalysis']:checked").each(
			function(i) {
				errorAnalysis += (i == 0 ? "" : ",")
						+ analysisReason[$(this).val()] + "";
			});
	if (errorAnalysis == "") {
		errorAnalysis = $('#txtAreaOtherReason').val();
	} else {
		errorAnalysis += "," + $('#txtAreaOtherReason').val();
	}
	var assignDate = $('#labAssignDate').html();
	var alarmId = $('#txtAlarmId').val();
	// var row = rowData;//$('#datagrid').datagrid('getData').rows[rowIndex];
	var data = {
		ifAlarmId : alarmId,
		errorAnalysis : errorAnalysis,
		assignDate : assignDate
	};
	$.ajax({
		type : "get",
		url : BASE_URL_API + '/serviceAlarmManagement/saveWorkOrder?v='
				+ Math.random(),
		dataType : 'json',
		data : data,
		contentType : "application/json",
		success : function(data) {
			if (data.result == true) {
				$("#datagrid").datagrid("reload");
				rowData=null;
				// $("#errormsg").html("ok").hide(3000);
				$('#winWorkOrder').window('close');
				$.messager.alert('提示', '<p>保存工单状成功!</p>', 'info');
				setTimeout(function() {
				}, 100);
			} else {
				$("#datagrid").datagrid("reload");
				$.messager.alert('错误', '<p>' + data.msg + '</p>', 'error');
				if(data.msg=='发送邮件失败'){
					rowData=null;
					// $("#errormsg").html("ok").hide(3000);
					$('#winWorkOrder').window('close');
					$.messager.alert('提示', '<p>保存工单状成功!</p>', 'info');
					setTimeout(function() {
					}, 100);
				}
			}
		},
		error : function() {
			$.messager.alert('错误', '<p>服务异常，保存工单失败，请稍后重试或联系管理员!</p>', 'error');
		}
	});
}
// 取消工单
function cancelWorkOrder() {	
	$('#winWorkOrder').window('close');
	// loopRefresh();
}
function getCurDate() {

	var curr_time = new Date();
	var year = curr_time.getFullYear();
	var month = curr_time.getMonth() + 1;
	var day = curr_time.getDate();
	var hours = curr_time.getHours();
	var minutes = curr_time.getMinutes();
	var seconds = curr_time.getSeconds();
	if (month < 10) {
		month = '0' + month;
	}
	if (day < 10) {
		day = '0' + day;
	}
	if (hours < 10) {
		hours = '0' + hours;
	}
	if (minutes < 10) {
		minutes = '0' + minutes;
	}
	if (seconds < 10) {
		seconds = '0' + seconds;
	}
	return year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':'
			+ seconds;
}
function analyze(rowIndex) {
	var row = $('#datagrid').datagrid('getData').rows[rowIndex];
	$('#labResCode').text(row.resCode);
	$('#labReqIp').text(row.reqIp);
	$('#labReqMethod').text(row.reqMethod);
	$('#labUrl').val(row.reqUrl.replace(/&lt;/g, "<").replace(/&gt;/g, ">"));

	$('#labReqMess').val(
			row.reqMess.replace(/&lt;/g, "<").replace(/&gt;/g, ">"));

	$('#labOccurDate').text(row.errorDateStr);
	$('#labPeakValue').text(row.peakValue + '秒');
	
	$('#labFlow').text(row.flow+'次');
	$('#labFlowThreshold').text(row.flowThreshold+'次');

	// 获取接口平均响应时间
	getIfAvgResTiems(rowIndex);

	$('#winExceptionIfAnalysis').window('open');
	$('#winExceptionIfAnalysis').window('setTitle', '服务异常分析:' + row.ifName);
}


function showWorkOrder(rowIndex) {	 
	var row = $('#datagrid').datagrid('getData').rows[rowIndex];   
	$('#txtAlarmId').val(row.id);
	rowData=row;	
	var type = row.alarmType;	
	type = (type == '1' ? '请求超时' : (type == '2' ? '请求超限' : 'Http400错误'));
	var level = row.alarmLevel;
	level = (level == '1' ? '一般告警' : (level == '2' ? '重要告警' : '紧急告警'));		
	$('#labAssignWorkCode').html(row.assignWorkCode);
	//alert(JSON.stringify(row));
	$('#labAlarmType').html(type);
	$('#labAssignDate').html(row.assignDateStr);	
	$('#labAlarmLevel').html(level);
	$('#labReceiver').html(row.errorReceiver);
	$('#txtAreaOtherReason').val('');
    $('input[name="chboxErrorAnalysis"]').attr("checked",false); 

//$("#winWorkOrder").siblings(".panel-header").children(".panel-tool")
//.children(".panel-tool-close").click(function(e) {
//// 定时刷新
//loopRefresh();
//});
	$('#winWorkOrder').window('open');
	$('#winWorkOrder').window('setTitle', '工单');	
}

function isolation(rowIndex) {
	$.messager.confirm('温馨提示', '<p>你真的要隔离么?</p>', function(result) {
		if (result) {
			var row = $('#datagrid').datagrid('getData').rows[rowIndex];
			var data = {
				ifAlarmId : row.id
			};
			$.ajax({
				type : "get",
				url : BASE_URL_API + '/serviceAlarmManagement/isolation?v='
						+ Math.random(),
				dataType : 'json',
				data : data,
				contentType : "application/json",
				success : function(data) {
					if (data.result == true) {
						// $("#errormsg").html("ok").hide(3000);
						$('#winWorkOrder').window('close');
						$.messager.alert('提示', '<p>接口隔离成功!</p>', 'info');
						setTimeout(function() {
							refresh();
						}, 100);
					} else {
						$.messager.alert('错误', '<p>' + data.msg + '</p>', 'error');
					}
				},
				error : function() {
					$.messager.alert('错误', '<p>服务异常，接口隔离失败，请稍后重试或联系管理员!</p>', 'error');
				}
			});
		}
	});

}
function cancelIsolation(rowIndex) {
	$.messager.confirm('温馨提示', '<p>你真的要取消隔离么?</p>', function(result) {
		if (result) {
			var row = $('#datagrid').datagrid('getData').rows[rowIndex];
			var data = {
				ifAlarmId : row.id
			};
			$.ajax({
				type : "get",
				url : BASE_URL_API + '/serviceAlarmManagement/cancelIsolation?v='
						+ Math.random(),
				dataType : 'json',
				data : data,
				contentType : "application/json",
				success : function(data) {
					if (data.result == true) {
						// $("#errormsg").html("ok").hide(3000);
						$('#winWorkOrder').window('close');
						$.messager.alert('提示', '<p>接口取消隔离成功!</p>', 'info');
						setTimeout(function() {
							refresh();
						}, 100);
					} else {
						$.messager.alert('错误', '<p>' + data.msg + '</p>', 'error');
					}
				},
				error : function() {
					$.messager.alert('错误', '<p>服务异常，接口取消隔离失败，请稍后重试或联系管理员!</p>', 'error');
				}
			});
		}
	});

}
function getIfAvgResTiems(rowIndex) {
	var row = $('#datagrid').datagrid('getData').rows[rowIndex]; // alert(JSON.stringify(row));
	var data = {
		ifId : row.ifId,
		date : row.inEsbDateStr,
		peakValue : row.peakValue
	};
	$.ajax({
		type : "get",
		url : BASE_URL_API + '/serviceAlarmManagement/findIfAvgResTiems?v='
				+ Math.random(),
		dataType : 'json',
		data : data,
		contentType : "application/json",
		success : function(data) {
			if (data.result == true) {
				// 将数据导入图表
				// alert(JSON.stringify(data.value));
				showCharts(data.value);
			} else {
				$.messager.alert('错误', '<p>' + data.msg + '</p>', 'error');
			}
		},
		error : function() {
			$.messager.alert('错误', '<p>服务异常，接口隔离失败，请稍后重试或联系管理员!</p>', 'error');
		}
	});
}
function showCharts(values) {
	var chart;
	$('#divAvgResTimes').highcharts(
			{
				chart : {				
						//去图表logo
					// renderTo : 'divAvgResTimes', // 图表放置的容器，DIV
					defaultSeriesType : 'spline'// , // 图表类型为曲线图
				},
				credits: { 
					enabled: false 
					},
				title : {
					text : 'RT-平均响应时间'// 图表标题
				},
				xAxis : { // 设置X轴
					type : 'datetime', // X轴为日期时间类型
					tickPixelInterval : 150
				// X轴标签间隔
				},
				yAxis : { // 设置Y轴
					title : '',
					max : 40, // Y轴最大值
					min : 0
				// Y轴最小值
				},
				tooltip : {// 当鼠标悬置数据点时的提示框
					formatter : function() { // 格式化提示信息
						return Highcharts.numberFormat(this.y, 3) + '秒';
					}
				},
				legend : {
				// enabled : true, // 设置图例不可见
				},
				exporting : {
					enabled : false
				// 设置导出按钮不可用
				},
				
				// credits : {
				// text : '平均响应时间'// , //设置LOGO区文字
				// // url: 'http://www.helloweba.com' //设置LOGO链接地址
				// },
				series : [ {
					name : '平均响应时间',
					data : (function() { // 设置默认数据，
						var data = [];
						$.each(values, function(i, item) {
							data.push({
								x : new Date(Date.parse((item.startDate)
										.replace(/-/g, "/"))).getTime(),
								y : item.avgResTimes
							});
						});

						return data;
					})()
				} ]
			});
	Highcharts.setOptions({
		global : {
			useUTC : false
		}
	});
}
// 查询
function search() {
	$('#datagrid').datagrid('reload');
}
function refresh() {
	$('#datagrid').datagrid('reload');
}
function chkChange(value){
	var disabled=false;
	$("[name='chboxPeriod']").each(function(){
		if($(this).val()==value){
			if ($(this).is(':checked')) {
				disabled=true;
			}
		}else{
			$(this).attr("checked", false);
		}
	});
	if(disabled){
		$("#txtStartDateTime").datetimebox({ disabled: true });
		$("#txtEndDateTime").datebox({ disabled: true });
		$('#txtStartDateTime').combo('setText',''); 
		$('#txtEndDateTime').combo('setText',''); 
	}else{
		$("#txtStartDateTime").datetimebox({ disabled: false });
		$("#txtEndDateTime").datebox({ disabled: false });
	}

}

function loopRefresh() {
	refresh();
	setTimeout(loopRefresh, 30000);
}

var loading_point = {
	timer : null,
	len : 3,
	count : 0
};
function loading() {
	if (loading_point.count < loading_point.len) {
		loading_point.count++;
		$("#progressbar_point").text($("#progressbar_point").text() + ".");
	} else {
		loading_point.count = 0;
		$("#progressbar_point").text("");
	}
}
